package com.ecar.oauth.provider.serviceImpl;

import com.ecar.core.common.dao.EcarUserMapper;
import com.ecar.core.common.dao.PrivilegeMapper;
import com.ecar.core.common.entity.EcarUser;
import com.ecar.core.common.entity.Privilege;
import com.ecar.core.common.entity.User;
import com.ecar.core.common.entity.SecurityUserDetails;
import com.ecar.oauth.provider.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Set;

/**
 * Created by 30 on 2016/4/15.
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private EcarUserMapper ecarUserMapper;
	
	@Autowired
	private PrivilegeMapper privilegeMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		EcarUser ecarUser = ecarUserMapper.findByUsername(username);
		Set<String> privileges= privilegeMapper.selectByUsername(username);
		if (ecarUser == null)
			throw new UsernameNotFoundException("Not found any user for username: [" + username + "]");
		return new SecurityUserDetails(ecarUser,privileges);
	}

	@Override
	public EcarUser loadCurrentUser() {
		EcarUser user;
		final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		final Object principal = authentication.getPrincipal();
		if (authentication instanceof OAuth2Authentication &&
			(principal instanceof String || principal instanceof org.springframework.security.core.userdetails.User)) {
			user = loadOauthUser((OAuth2Authentication) authentication);
		} else {
			final SecurityUserDetails userDetails = (SecurityUserDetails) principal;
			user = ecarUserMapper.findByUsername(userDetails.getUsername());
		}
		return user;
	}

	private EcarUser loadOauthUser(OAuth2Authentication authentication) {
		EcarUser user = new EcarUser();
		user.setUsername(authentication.getName());

		final Collection<GrantedAuthority> authorities = authentication.getAuthorities();
		for (GrantedAuthority authority : authorities) {
			Privilege privilege = new Privilege();
			privilege.setPrivilege(authority.getAuthority());
		}
		return user;
	}

}
